# from flasgger import swag_from
from flask import request, jsonify
from routes import app
from datetime import datetime
import jwt
import datetime
from flask_login import login_user, current_user, logout_user, login_required
from services.user_service import UserService,RegulationDataService

userService = UserService()

def generate_token(username):
    expiration = datetime.datetime.utcnow() + datetime.timedelta(hours=8) # minutes=1 代表1分钟后过期 hours
    token = jwt.encode({'username': username, 'exp': expiration}, app.config['SECRET_KEY'], algorithm='HS256')
    return token


@app.route('/api/register', methods=['POST'])
def api_register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')

    if not username or not password or not email:
        return jsonify({'message': 'Missing required fields'}), 400

    try:
        userService.register_user(username=username, password=password, email=email)
        token = generate_token(username)
        return jsonify({'token': token, 'message': '注册成功'}), 201
    except ValueError as e:
        return jsonify({'message': str(e)}), 409


@app.route('/api/login', methods=['POST'])
def api_login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    user = userService.authenticate_user(username, password) # 进行用户认证。
    #如果用户名和密码匹配，返回对应的用户对象；否则返回 None。
    if user:
        login_user(user)
        token = generate_token(username)
        return jsonify({'token': token, 'message': '登录成功'}), 200
    else:
        return jsonify({'message': '用户名或密码错误'}), 401


@app.route('/api/logout', methods=['POST'])
def api_logout():
    # if not current_user.is_authenticated:
    #     return jsonify({'message': '未登录'}), 401

    logout_user()
    return jsonify({'message': '已退出登录'}), 200

"""
调节服务项的数据接口
==============================================================================
"""

regulationDataService = RegulationDataService()
@app.route("/regulation_services", methods=['GET', 'POST'])
# @login_required
def regulation_services():
    if request.method == 'POST':
        data = request.json
        try:
            regulation_service = regulationDataService.add_regulation_service(data)
            return jsonify(regulation_service.to_dict()), 201
        except ValueError as e:
            return jsonify({'error': str(e)}), 400
    elif request.method == 'GET':
        regulation_services = regulationDataService.get_all_regulation_services()
        return jsonify([service.to_dict() for service in regulation_services]), 200

@app.route("/regulation_services/<int:id>", methods=['GET', 'PUT', 'DELETE'])
# @login_required
def regulation_service(id):
    if request.method == 'GET':
        try:
            regulation_service = regulationDataService.get_regulation_service(id)
            return jsonify(regulation_service.to_dict()), 200
        except ValueError as e:
            return jsonify({'error': str(e)}), 404
    elif request.method == 'PUT':
        data = request.json
        try:
            updated_service = regulationDataService.update_regulation_service(id, data)
            return jsonify(updated_service.to_dict()), 200
        except ValueError as e:
            return jsonify({'error': str(e)}), 400
    elif request.method == 'DELETE':
        try:
            if regulationDataService.delete_regulation_service(id):
                return jsonify({'message': 'Deleted successfully'}), 200
            else:
                return jsonify({'error': 'Not found'}), 404
        except ValueError as e:
            return jsonify({'error': str(e)}), 400

@app.route("/regulation_services_by_fields/<int:year>/<string:gepCity>/<string:gepDistrict>/<string:gepTown>", methods=['GET', 'PUT', 'DELETE'])
def regulation_service_by_fields(year, gepCity, gepDistrict, gepTown):
    if request.method == 'GET':
        print("get", year, gepCity, gepDistrict, gepTown)
        record = regulationDataService.get_regulation_service_by_fields(year, gepCity, gepDistrict, gepTown)
        if record:
            return jsonify(record.to_dict()), 200
        else:
            return jsonify({'error': 'Not found'}), 404

    elif request.method == 'PUT':
        data = request.json
        updated_record = regulationDataService.update_regulation_service_by_fields(year, gepCity, gepDistrict, gepTown, data)
        if updated_record:
            return jsonify(updated_record.to_dict()), 200
        else:
            return jsonify({'error': 'Not found or failed to update'}), 404

    elif request.method == 'DELETE':
        deleted = regulationDataService.delete_regulation_service_by_fields(year, gepCity, gepDistrict, gepTown)
        if deleted:
            return jsonify({'message': 'Deleted successfully'}), 200
        else:
            return jsonify({'error': 'Not found'}), 404
